package com.suian.intercept;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class MyRestTemplateIntercept implements ClientHttpRequestInterceptor {
    private static final Logger log = LoggerFactory.getLogger(MyRestTemplateIntercept.class);

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        // 记录请求信息
        logRequest(request, body);

        // 执行请求
        ClientHttpResponse response = execution.execute(request, body);
        // 缓存响应体
        byte[] responseBody = StreamUtils.copyToByteArray(response.getBody());

        // 重新包装响应对象，确保后续可读取
        ClientHttpResponse wrappedResponse = new BufferedClientHttpResponseWrapper(response, responseBody);

        // 记录响应信息（可选）
        logResponse(response);
        return wrappedResponse;
    }

    private void logResponse(ClientHttpResponse response) throws IOException {
        log.info("====== RestTemplate Response Start ======");
        log.info("Status  : {}", response.getStatusCode());
        log.info("Headers : {}", response.getHeaders());
        log.info("Body    : {}", StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8));
        log.info("====== RestTemplate Response End ======");
    }

    private void logRequest(HttpRequest request, byte[] body) {
        log.info("====== RestTemplate Request Start ======");
        log.info("URI     : {}", request.getURI());
        log.info("Method  : {}", request.getMethod());
        log.info("Headers : {}", request.getHeaders());
        log.info("Body    : {}", new String(body, StandardCharsets.UTF_8));
        log.info("====== RestTemplate Request End ======");

    }


    private static class BufferedClientHttpResponseWrapper implements ClientHttpResponse {
        private final ClientHttpResponse originalResponse;
        private final byte[] body;
        public BufferedClientHttpResponseWrapper(ClientHttpResponse response, byte[] responseBody) {
            this.originalResponse = response;
            this.body = responseBody;
        }
        @Override
        public InputStream getBody() {
            return new ByteArrayInputStream(body);
        }


        @Override
        public HttpStatusCode getStatusCode() throws IOException {
            return originalResponse.getStatusCode();
        }

        @Override
        public String getStatusText() throws IOException {
            return originalResponse.getStatusText();
        }

        @Override
        public void close() {
            originalResponse.close();
        }

        @Override
        public org.springframework.http.HttpHeaders getHeaders() {
            return originalResponse.getHeaders();
        }
    }
}

